import curses
import random

class SnakeGame:
    def __init__(self):
        self.screen = curses.initscr()
        curses.curs_set(0)
        self.height, self.width = self.screen.getmaxyx()
        self.snake = [[self.height//2, self.width//4]]
        self.food = self._generate_food()
        self.score = 0
        self.direction = curses.KEY_RIGHT
        self.screen.keypad(True)
        self.screen.timeout(100)

    def _generate_food(self):
        while True:
            food = [random.randint(1, self.height-2), 
                   random.randint(1, self.width-2)]
            if food not in self.snake:
                return food

    def _draw(self, char, pos):
        try:
            self.screen.addch(pos[0], pos[1], char)
        except curses.error:
            pass

    def run(self):
        while True:
            next_key = self.screen.getch()
            self.direction = next_key if next_key != -1 else self.direction
            
            if self._check_collision():
                curses.endwin()
                print(f"Game Over! Score: {self.score}")
                break
                
            self._move_snake()
            self.screen.clear()
            self._draw(curses.ACS_PI, self.food)
            for segment in self.snake:
                self._draw(curses.ACS_CKBOARD, segment)
            self.screen.addstr(0, 2, f"Score: {self.score}")
            self.screen.refresh()

    def _move_snake(self):
        head = [self.snake[0][0], self.snake[0][1]]
        
        if self.direction == curses.KEY_UP:
            head[0] -= 1
        elif self.direction == curses.KEY_DOWN:
            head[0] += 1
        elif self.direction == curses.KEY_LEFT:
            head[1] -= 1
        elif self.direction == curses.KEY_RIGHT:
            head[1] += 1
            
        self.snake.insert(0, head)
        
        if head == self.food:
            self.score += 1
            self.food = self._generate_food()
        else:
            self.snake.pop()

    def _check_collision(self):
        return (self.snake[0][0] in [0, self.height-1] or 
                self.snake[0][1] in [0, self.width-1] or 
                self.snake[0] in self.snake[1:])

if __name__ == "__main__":
    game = SnakeGame()
    game.run()
